package com.pl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.net.NetUtil;
import cn.hutool.core.util.RandomUtil;
import com.pl.client.IOpsClient;
import com.pl.event.*;
import com.pl.util.Constant;
import com.pl.util.OpsConfig;
import com.pl.util.TimeUtil;
import io.micrometer.core.instrument.Counter;
import io.micrometer.core.instrument.Meter;
import io.micrometer.core.instrument.Metrics;
import io.micrometer.core.instrument.Timer;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@Component
public class OpsJob {
    /*  38 */   private final Logger log = LoggerFactory.getLogger(OpsJob.class);


    @Autowired
    private IOpsClient agentClient;


    @Autowired
    private Environment env;


    /*  50 */   private int randomSecond = RandomUtil.randomInt(1, 55);


    @Async
    @Scheduled(cron = "0/1 * * * * ?")
    public void methodStats() {
        /*  56 */
        if (Calendar.getInstance().get(13) == this.randomSecond) {
            /*  57 */
            String timestamp = TimeUtil.lastMinuteTimeMuniteStr();
            /*  58 */
            String currentTimestmp = TimeUtil.currentTimeMinuteStr();

            /*  60 */
            String serviceIp = getLocalIp();
            /*  61 */
            Integer port = getServicePort();
            /*  62 */
            String application = getApplication();
            /*  63 */
            String project = getProject();
            /*  64 */
            String nextMinute = DateUtil.format(new Date(), "yyyy-MM-dd HH:mm");
            /*  65 */
            List<MethodOpsModel> methodOpsModelList = new ArrayList<>();

            /*  67 */
            DateTime minute = DateUtil.parse(timestamp, "yyyy-MM-dd HH:mm");
            /*  68 */
            for (String methodSignature : Constant.methodSignatureSet) {
                try {
                    /*  70 */
                    Timer timer = Metrics.timer("method.invoke.perf", new String[]{"method.tag.signature", methodSignature, "method.tag.timestamp", timestamp});


                    /*  73 */
                    Counter failCounter = Metrics.counter("method.invoke.count.fail", new String[]{"method.tag.signature", methodSignature, "method.tag.timestamp", timestamp});

                    /*  75 */
                    long failCount = (long) failCounter.count();

                    /*  77 */
                    String[] methodInfo = methodSignature.split(":");

                    /*  79 */
                    MethodOpsModel model = new MethodOpsModel(methodInfo[0], methodInfo[1], (Date) minute, timer.count(), failCount, timer.mean(TimeUnit.MILLISECONDS), timer.max(TimeUnit.MILLISECONDS));

                    /*  81 */
                    methodOpsModelList.add(model);


                    /*  84 */
                    Metrics.globalRegistry.remove((Meter) timer);
                    /*  85 */
                    Metrics.globalRegistry.remove((Meter) failCounter);



                    /*  89 */
                    Timer nextTimer = Metrics.timer("method.invoke.perf", new String[]{"method.tag.signature", methodSignature, "method.tag.timestamp", nextMinute});

                    /*  91 */
                    if (nextTimer.count() == 0L) {
                        /*  92 */
                        Constant.methodSignatureSet.remove(methodSignature);
                    }
                    /*  94 */
                } catch (Exception e) {
                    /*  95 */
                    this.log.warn("collect method stats error for {}", methodSignature, e);
                }
            }


            try {
                /* 101 */
                MethodOpsEvent event = new MethodOpsEvent(project, serviceIp, port, application, methodOpsModelList, null);
                /* 102 */
                this.agentClient.sendMethodOpsEvent(event);
                /* 103 */
            } catch (Exception e) {
                /* 104 */
                this.log.warn("send method stats error", e);
            }


            /* 108 */
            Set<String> keys = new HashSet<>(Constant.exceptionMap.keys().elementSet());
            /* 109 */
            for (String key : keys) {
                /* 110 */
                if (currentTimestmp.equals(key)) {
                    continue;
                }
                try {
                    /* 114 */
                    List<MethodExceptionModel> methodExceptionModelList = new ArrayList<>(Constant.exceptionMap.get(key));
                    /* 115 */
                    MethodOpsEvent exceptionEvent = new MethodOpsEvent(project, serviceIp, port, application, null, methodExceptionModelList);
                    /* 116 */
                    this.agentClient.sendMethodOpsEvent(exceptionEvent);
                    /* 117 */
                } catch (Exception e) {
                    /* 118 */
                    this.log.warn("send exception stats error", e);
                } finally {

                    /* 121 */
                    Constant.exceptionMap.removeAll(key);
                }
            }
        }
    }

    @Async
    @Scheduled(cron = "0/1 * * * * ?")
    public void bizLogStats() {
        /* 130 */
        if (Calendar.getInstance().get(13) == this.randomSecond) {

            /* 132 */
            String currentTimestamp = TimeUtil.currentTimeMinuteStr();
            /* 133 */
            Set<String> keys = new HashSet<>(Constant.GLOBAL_BIZ_LOG_MAP.keys().elementSet());
            /* 134 */
            String serviceIp = getLocalIp();
            /* 135 */
            Integer port = getServicePort();
            /* 136 */
            for (String key : keys) {
                /* 137 */
                if (currentTimestamp.equals(key)) {
                    continue;
                }
                try {
                    /* 141 */
                    Collection<BizLogOpsModel> bizLogOpsModels = Constant.GLOBAL_BIZ_LOG_MAP.get(key);
                    /* 142 */
                    if (bizLogOpsModels != null && !bizLogOpsModels.isEmpty()) {
                        /* 143 */
                        List<BizLogOpsModel> bizLogOpsModellList = new ArrayList<>(bizLogOpsModels);

                        /* 145 */
                        String application = getApplication();
                        /* 146 */
                        BizLogOpsEvent event = new BizLogOpsEvent(serviceIp, port, getProject(), application, bizLogOpsModellList);
                        /* 147 */
                        this.agentClient.sendBizLogOpsEvent(event);
                    }
                    /* 149 */
                } catch (Exception e) {
                    /* 150 */
                    this.log.warn("bizLogStats error", e);
                } finally {
                    /* 152 */
                    Constant.GLOBAL_BIZ_LOG_MAP.removeAll(key);
                }
            }
        }
    }

    private Integer getServicePort() {
        try {
            /* 160 */
            return Integer.valueOf(this.env.getProperty("server.port"));
            /* 161 */
        } catch (NumberFormatException e) {
            /* 162 */
            this.log.warn("getServicePort error", e);
            /* 163 */
            return null;
        }
    }

    private String getLocalIp() {
        /* 168 */
        String host = this.env.getProperty("spring.cloud.consul.discovery.hostname");
        /* 169 */
        if (host == null) {
            try {
                /* 171 */
                host = NetUtil.getLocalhostStr();
                /* 172 */
            } catch (Exception e) {
                /* 173 */
                this.log.error("get server host Exception e:", e);
                /* 174 */
                return null;
            }
        }

        /* 178 */
        return host;
    }

    public String getApplication() {
        /* 182 */
        if (OpsConfig.getApplication() != null) {
            /* 183 */
            return OpsConfig.getApplication();
        }
        /* 185 */
        String host = this.env.getProperty("spring.cloud.consul.discovery.serviceName");
        /* 186 */
        if (host == null) {
            /* 187 */
            host = this.env.getProperty("spring.application.name");
        }

        /* 190 */
        return host;
    }

    public String getProject() {
        /* 194 */
        if (OpsConfig.getProject() != null) {
            /* 195 */
            return OpsConfig.getProject();
        }
        /* 197 */
        String project = this.env.getProperty("mos.ops.project");
        /* 198 */
        if (project == null) {
            /* 199 */
            project = this.env.getProperty("project");
        }
        /* 201 */
        return project;
    }
}


/* Location:              E:\code\common\cmsr-common-ops-log\1.0.0-SNAPSHOT\cmsr-common-ops-log-1.0.0-SNAPSHOT.jar!\com\cmsr\common\ops\log\OpsJob.class
 * Java compiler version: 8 (52.0)
 * JD-Core Version:       1.1.3
 */